package com.guigui.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigui.common.utils.PageUtils;
import com.guigui.common.utils.Query;
import com.guigui.gulimall.product.dao.CategoryDao;
import com.guigui.gulimall.product.entity.CategoryBrandRelationEntity;
import com.guigui.gulimall.product.entity.CategoryEntity;
import com.guigui.gulimall.product.service.CategoryBrandRelationService;
import com.guigui.gulimall.product.service.CategoryService;
import com.guigui.gulimall.product.vo.web.CatalogListWebVo;
import com.mysql.cj.util.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 分布式锁
     */
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有记录，并生成树形结构
     *
     * @return: []
     * @Author: xin
     * @Date: 2021/7/25 14:35
     */
    @Override
    public List<CategoryEntity> listAsTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> collect = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(categoryEntity -> {
            categoryEntity.setChildren(findChildren(categoryEntity, entities));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 逻辑删除
     *
     * @return: [java.util.List<java.lang.Long>]
     * @Author: xin
     * @Date: 2021/7/26 11:14
     */
    @Override
    public void removeCategoryByIds(List<Long> asList) {
        //TODO 逻辑删除未实现
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 加入redis缓存
     */
    @Override
    @Cacheable(value = "catalog", key = "#root.method.name")
    public Map<String, List<CatalogListWebVo>> getCatalogJson() {
        // 1、设置null值，防止缓存穿透
        // 2、多线程进来的时候加锁，防止击穿
        // 3、设置随机的过期时间，防止雪崩

        String token = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", token, 100, TimeUnit.SECONDS);
        try {
            if (lock != null && lock) {
                String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");
                if (StringUtils.isNullOrEmpty(catalogJson)) {
                    return getCatalogJsonOnDb();
                }
                return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<CatalogListWebVo>>>() {
                });
            } else {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCatalogJson();
            }
        } finally {
            String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            stringRedisTemplate.execute(new DefaultRedisScript<>(lua, Long.class), Collections.singletonList("lock"), token);
        }

    }

    public Map<String, List<CatalogListWebVo>> getCatalogJsonByTest() {
        // 1、设置null值，防止缓存穿透
        // 2、多线程进来的时候加锁，防止击穿
        // 3、设置随机的过期时间，防止雪崩

        String token = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", token, 100, TimeUnit.SECONDS);
        try {
            if (lock != null && lock) {
                String catalogJson = stringRedisTemplate.opsForValue().get("catalogJson");

                if (StringUtils.isNullOrEmpty(catalogJson)) {
                    Map<String, List<CatalogListWebVo>> catalogJsonOnDb = getCatalogJsonOnDb();
                    String serialJson = JSON.toJSONString(catalogJsonOnDb);
                    // null值加标志位
                    if (catalogJsonOnDb == null) {
                        serialJson = "0";
                    }
                    // 设置随机时间过期

                    stringRedisTemplate.opsForValue().set("catalogJson", serialJson, 1L, TimeUnit.HOURS);
                    return catalogJsonOnDb;
                }

                System.out.println("命中缓存");
                return "0".equals(catalogJson) ? null : JSON.parseObject(catalogJson, new TypeReference<Map<String, List<CatalogListWebVo>>>() {
                });
            } else {
                System.out.println("自旋");
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCatalogJson();
            }
        } finally {
            String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<>(lua, Long.class), Collections.singletonList("lock"), token);
        }

    }

    /**
     * 查询一级分类
     */
    @Cacheable(value = "catalog", key = "#root.method.name")
    @Override
    public List<CategoryEntity> getCatalogLevelOne() {
        return this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @CacheEvict(value = "catalog", allEntries = true)
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void updateByCategory(CategoryEntity category) {
        this.updateById(category);

        // 级联更新分类名
        categoryBrandRelationService.update(
                new UpdateWrapper<CategoryBrandRelationEntity>()
                        .eq("catelog_id",category.getCatId())
                        .set("catelog_name",category.getName())
        );
    }

    /**
     * 查询json格式的分类
     */
    @Cacheable(value = "catalog", key = "#root.methodName")
    public Map<String, List<CatalogListWebVo>> getCatalogJsonOnDb() {
        List<CategoryEntity> categoryList = this.list();

        List<CategoryEntity> level1 = categoryList.stream().filter(category -> category.getCatLevel().equals(1)).collect(Collectors.toList());
        List<CategoryEntity> level2 = categoryList.stream().filter(category -> category.getCatLevel().equals(2)).collect(Collectors.toList());
        List<CategoryEntity> level3 = categoryList.stream().filter(category -> category.getCatLevel().equals(3)).collect(Collectors.toList());

        Map<String, List<CatalogListWebVo>> collect1 = level1.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), l1 -> {

            // 按照l1对象，过滤出2级子对象
            List<CategoryEntity> l2ListByParentIdList = level2.stream().filter(l2 -> l2.getParentCid().equals(l1.getCatId())).collect(Collectors.toList());

            //子对象映射为CatalogListWebVo集合
            List<CatalogListWebVo> collect = l2ListByParentIdList.stream().map(l2 -> {
                CatalogListWebVo catalogListWebVo = new CatalogListWebVo();
                catalogListWebVo.setCatalog1Id(l2.getParentCid().toString());
                catalogListWebVo.setId(l2.getCatId().toString());
                catalogListWebVo.setName(l2.getName());


                // 按照l2对象，过滤出3级子对象
                List<CategoryEntity> l3ListByParentIdList = level3.stream().filter(l3 -> l3.getParentCid().equals(l2.getCatId())).collect(Collectors.toList());

                // 子对象映射为 Catalog3List 集合
                List<CatalogListWebVo.Catalog3List> collect2 = l3ListByParentIdList.stream().map(l3 -> {
                    CatalogListWebVo.Catalog3List catalog3 = new CatalogListWebVo.Catalog3List();
                    catalog3.setName(l3.getName());
                    catalog3.setCatalog2Id(l2.getCatId().toString());
                    catalog3.setId(l3.getCatId().toString());

                    return catalog3;
                }).collect(Collectors.toList());

                catalogListWebVo.setCatalog3List(collect2);
                return catalogListWebVo;
            }).collect(Collectors.toList());

            return collect;
        }));


        return collect1;
    }

    private List<CategoryEntity> findChildren(CategoryEntity root, List<CategoryEntity> parent) {
        List<CategoryEntity> collect = parent.stream().filter((pCategory) -> {
            return Objects.equals(pCategory.getParentCid(), root.getCatId());
        }).map((categoryEntity) -> {
            //子菜单
            categoryEntity.setChildren(findChildren(categoryEntity, parent));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}